from enum import Enum
from datetime import datetime
import sys
import re
import logging as l
from model import *

position_pat = re.compile(r'#(?P<aStart>\d+)(-(?P<aEnd>\d+))?|第 (?P<bStart>\d+)(-(?P<bEnd>\d+))? 页')
date_pat = re.compile(r'(?P<year>\d{4})年(?P<month>\d+)月(?P<day>\d+)日')
time_pat = re.compile(r'((?P<am>上午)|(?P<pm>下午))(?P<hour>\d+):(?P<minute>\d+):(?P<second>\d+)')

def parse_single_entry(entry:str) -> Note:
    """解析一个笔记条目"""
    lines = entry.split('\n')
    book = lines[0].strip()

    # 解析失败
    if len(book) == 0: return None
    # 解析位置以及时间，还有类型
    position_match = position_pat.search(lines[1])
    date_match = date_pat.search(lines[1])
    time_match = time_pat.search(lines[1])

    if position_match is None or date_match is None or time_match is None:
        l.fatal('failed to parse entry: %s' % (entry))
        l.fatal(position_match)
        l.fatal(date_match)
        l.fatal(time_match)
        sys.exit(-1)

    # 解析位置类型
    if position_match.group('aStart'): #kindle 页码
        end = position_match.group('aEnd')
        if end:
            end = int(end)
        position = KindleRange(int(position_match.group('aStart')), end)
    elif position_match.group('bStart'): #普通页码
        end = position_match.group('bEnd')
        if end:
            end = int(end)
        position = PageRange(int(position_match.group('bStart')), end)
    else:
        l.fatal('something went wrong with position parsing in entry: %s' % (entry))
        sys.exit(-1)

    # 解析时间
    year = date_match.group('year')
    month = date_match.group('month')
    day = date_match.group('day')
    minute = time_match.group('minute')
    second = time_match.group('second')
    hour = time_match.group('hour')
    if time_match.group('pm'):
        if hour != '12':
            hour = int(hour) + 12
    #print(hour)

    dt = datetime(int(year), int(month), int(day), hour=int(hour), minute=int(minute), second=int(second))

    # 笔记类型
    if '笔记' in lines[1]:
        # 笔记类型
        note = Comment()
    elif '标注' in lines[1]:
        # 标注类型
        note = Highlighting()
    elif '书签' in lines[1]:
        # 书签
        note = Bookmark()
    else:
        l.fatal('failed to determine type of entry %s' % (entry))
        sys.exit(-1)

    # 笔记内容
    note.book = book
    note.content = '\n'.join(filter(lambda s:s, lines[3:]))
    note.position = position
    note.time = dt
    return note

def parse(filename):
    note_list = []
    position_pat = re.compile(r'#(?P<range>\d+(-\d+)?)|第 (?P=range) 页')
    date_pat = re.compile(r'(\d{4})年(\d+)月(\d+)日')
    time_pat = re.compile(r'(\d+:\d+:\d+)')
    with open(filename, 'r') as f:
        data = f.read()
        entry_list = data.split('==========\n')
        for entry in entry_list:
            note = parse_single_entry(entry)
            if note:
                note_list.append(note)
    return note_list

if __name__ == '__main__':
    data = parse('./My Clippings.txt')
    print(data[-1].content)
    print(data[-10:])
